<template>
  <div style="text-align: center;">
    <div>
      <canvas ref="qrcode"></canvas>
    </div>
    <el-form label-width="40px">
      <el-form-item prop="address" label="URL">
        <el-input ref="text" v-model="address" :readonly="true"></el-input>
      </el-form-item>
      <el-button type="primary" @click="copyLink(address)">复制</el-button>
    </el-form>
  </div>
</template>
<style>

</style>
<script>
import QRCode from 'qrcode';

export default {
  props: {
    address: String,
  },
  data() {
    return {};
  },
  mounted() {
    QRCode.toCanvas(this.$refs.qrcode, this.address, (err) => {
      if (err) {
        console.log(err);
      } else {
        console.log('success');
      }
    });
  },
  beforeUpdate() {
    QRCode.toCanvas(this.$refs.qrcode, this.address, (err) => {
      if (err) {
        console.log(err);
      } else {
        console.log('update', this.address);
      }
    });
  },
  methods: {
    copyLink(link) {
      const input = document.createElement('input');
      this.$refs.text.$el.appendChild(input);
      input.setAttribute('value', link);
      input.select();
      // this.$refs.text.$el.children[0].select();
      if (document.execCommand('copy')) {
        document.execCommand('copy');
        this.$message({
          type: 'success',
          message: '复制成功!',
        });
        console.log('复制成功');
      } else {
        this.$message({
          type: 'waring',
          message: '你的浏览器不支持复制，请手动复制',
        });
      }
      this.$refs.text.$el.removeChild(input);
    },
  },
};
</script>

